package com.lq.gateway.filter;

import com.lq.common.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * JWT鉴权过滤器
 */
@Component
public class JwtAuthenticationFilter implements GlobalFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
    
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    // 白名单路径 - 不需要鉴权的路径
    private static final List<String> WHITE_LIST = List.of(
            "/api/users/login",
            "/api/users/register",
            "/api/users/logout"
    );
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        
        // 获取请求路径
        String path = request.getURI().getPath();
        log.debug("请求路径: {}", path);
        
        // 检查是否在白名单中
        if (isWhitelisted(path)) {
            log.debug("路径 {} 在白名单中，跳过鉴权", path);
            return chain.filter(exchange);
        }
        
        // 从请求头中获取Authorization
        String authHeader = request.getHeaders().getFirst("Authorization");
        
        // 检查Authorization是否存在
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            log.warn("缺少有效的Authorization头: {}", path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        
        // 提取JWT Token
        String jwt = authHeader.substring(7);
        
        try {
            // 验证JWT Token
            String username = JwtUtil.extractUsername(jwt);
            Integer userid = JwtUtil.extractClaimId(jwt);
            if (username == null || username.isEmpty() || !JwtUtil.validateToken(jwt, username)) {
                log.warn("无效的JWT Token: {}", path);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            
            log.debug("JWT Token验证通过: {}", username);
            // 将用户信息添加到请求头中，供下游服务使用
            ServerHttpRequest mutatedRequest = request.mutate()
                    .header("X-User-Name", username)
                    .header("X-User-Id", String.valueOf(userid))
                    .build();
            
            return chain.filter(exchange.mutate().request(mutatedRequest).build());
        } catch (Exception e) {
            log.error("JWT Token解析失败: {}", e.getMessage(), e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
    
    /**
     * 检查路径是否在白名单中
     * @param path 请求路径
     * @return 是否在白名单中
     */
    private boolean isWhitelisted(String path) {
        return WHITE_LIST.stream().anyMatch(pattern -> pathMatcher.match(pattern, path));
    }
    
    @Override
    public int getOrder() {
        return -100; // 设置过滤器优先级，数值越小优先级越高
    }
}